import json
import logging
import os
import webapp2

from db.student_client import StudentClient
from google.appengine.api import users
from service.service_handler import ServiceHandler
from tmpl import tmpl_util

# Students that can view the site before it's launched.
VALID_PREVIEW_STUDENTS = [
  'jcabrera@marywood.edu',
  'jcabrera@maryu.marywood.edu',
  'ncabrera@gmail.com',
  'jnajarian@m.marywood.edu',
  'elopez@m.marywood.edu',
  'jackerman@m.marywood.edu',
  'bdomahidi@m.marywood.edu',
  'iposhka@m.marywood.edu'
]


def isDevMode(request):
  if (not request.params.has_key('compiled') and
      os.environ['SERVER_SOFTWARE'].startswith('Development')):
    return True
  return False


class MainPage(webapp2.RequestHandler):
  def get(self):
    is_dev_mode = isDevMode(self.request)

    if not is_dev_mode:
      # Redirect if not secure or if domain starts with "www".
      if ((os.environ.has_key('HTTPS') and os.environ['HTTPS'] == 'off') or
          os.environ['HTTP_HOST'] == 'www.muresidencestudy.appspot.com'):
        self.redirect('https://muresidencestudy.appspot.com')
        return

    student_client = StudentClient()
    user = users.get_current_user()

    # student_client.deleteAllStudents()
    # student_client.loadStudents(is_new_year=True)

    students = student_client.getStudentsForWeb()
     
    # If we're in DEV mode then load our students if they haven't already been
    # loaded.
    if is_dev_mode and len(students) == 0:
      student_client.loadStudents(is_new_year=True)
      students = student_client.getStudentsForWeb()
    
    if not user:
      self.redirect(users.create_login_url(self.request.uri))
      return
    
    user_student_id = student_client.getStudentIdForUser(user)
    
    if not user_student_id:
      self.redirect('/invaliduser')
      return
      
    # Get the student model for this user.
    user_student_model = student_client.getStudent(user_student_id)
     
    self.response.out.write(
        tmpl_util.getMain(user, user_student_model, students, is_dev_mode))


class ServiceRequestHandler(webapp2.RequestHandler):
  def post(self):
    student_client = StudentClient()
    user = users.get_current_user()
    if not user or not student_client.getStudentIdForUser(user):
      self.redirect(users.create_login_url(self.request.uri))
      return

    call_response = ServiceHandler.handleRequest(
        user,
        self.request.get('service'),
        self.request.get('method'),
        json.loads(self.request.get('request')))
    self.response.out.write(json.dumps(call_response))


class PrizesPage(webapp2.RequestHandler):
  def get(self):
    is_dev_mode = isDevMode(self.request)
    student_client = StudentClient()
    user = users.get_current_user()
    if not user or not student_client.getStudentIdForUser(user):
      self.redirect(users.create_login_url(self.request.uri))
      return

    self.response.out.write(
        tmpl_util.getPrizes(user, is_dev_mode))


app = webapp2.WSGIApplication([
  ('/', MainPage),
  ('/service', ServiceRequestHandler),
  ('/prizes', PrizesPage)
], debug=True)
